package com.guochaojava.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.guochaojava.config.PropertiesConfig;
import com.guochaojava.dao.MemberMapper;
import com.guochaojava.model.Member;
import com.guochaojava.model.enums.MemberStatusEnum;
import com.guochaojava.param.MemberParam;
import com.guochaojava.service.MemberService;
import com.lgd.winter.wechat.content.tecent.bean.result.TecentAccessTokenResult;
import com.lgd.winter.wechat.core.WeChatTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 会员业务层实现
 *
 * @author guochao
 * @since 1.0.0
 */
@Service
public class MemberServiceImpl implements MemberService {

    private static final int ROOT_PORT = 80;

    @Autowired
    private MemberMapper dao;
    @Autowired
    private WeChatTemplate weChatTemplate;
    @Autowired
    private PropertiesConfig propertiesConfig;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return dao.deleteByPrimaryKey(id);
    }

    @Override
    public int insertSelective(MemberParam record, HttpServletRequest request) {
        //查询是否添加过
        Member oldMember = dao.selectByOpenId(record.getOpenId());
        if (oldMember != null) {
            //已有记录 直接返回
            return 0;
        }
        Member member = new Member();
        BeanUtils.copyProperties(record, member);
        //创建时间
        member.setCreateTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        dao.insertSelective(member);

        //创建二维码
        String path = getQrCode(weChatTemplate, member.getId(), request);
        member.setQrCode(path);

        return dao.updateByPrimaryKeySelective(member);
    }

    @Override
    public Member selectByPrimaryKey(Integer id) {
        return dao.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Member record) {
        return dao.updateByPrimaryKeySelective(record);
    }

    @Override
    public Member selectByOpenId(String openId) {
        return dao.selectByOpenId(openId);
    }

    @Override
    public Member start(String openId) {
        Member member = dao.selectByOpenId(openId);
        member.setStatus(MemberStatusEnum.PLAYING.getCode());
        dao.updateByPrimaryKeySelective(member);
        return member;
    }

    @Override
    public int rank(Integer id) {
        return dao.rank(id);
    }

    private String getQrCode(WeChatTemplate weChatTemplate, Integer id, HttpServletRequest request) {
        String returnStr = "";

        TecentAccessTokenResult accessTokenResult = weChatTemplate.opsForTecent().getAccessToken();
        if (accessTokenResult.getErrcode() != 0) {
            return "";
        }
        String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessTokenResult.getAccessToken();
        String basePath = "";
        //获取系统信息
        String os = System.getProperty("os.name");
        // 用于判断是windows还是linux
        if (os.toLowerCase().startsWith("win")) {
            // windows   D:\\upload
            basePath = propertiesConfig.getUpload().getWindows();
        } else {
            // linux   /home/upload
            basePath = propertiesConfig.getUpload().getLinux();
        }
        returnStr = "/qrcode/" + DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".jpg";

        basePath = basePath + returnStr;

        Map<String, Object> map = new HashMap<String, Object>(2);
        map.put("path","pages/belnningGame/belnningGame?id="+id);
        String a = JSONUtil.toJsonStr(map);
        HttpRequest b = HttpUtil.createPost(url);
        b.body(a);
        HttpResponse c = b.execute();
        InputStream d = c.bodyStream();
        try {
            OutputStream outputStream = new FileOutputStream(new File(basePath));
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = d.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.close();
            d.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return getBaseUrl(request) + "/upload" + returnStr;
    }

    public String getBaseUrl(HttpServletRequest request) {
        String appContext = request.getContextPath();
        StringBuilder basePath = new StringBuilder();
        basePath.append(request.getScheme()).append("://");
        basePath.append(request.getServerName());
        if (request.getServerPort() != ROOT_PORT) {
            basePath.append(":").append(request.getServerPort());
        }
        basePath.append(appContext);
        return basePath.toString();
    }
}